import configparser
import json
import logging
import os

from common.logger import logger

config_rew_path = "./config-rew.properties"

# 读取properties文件工具函数
def load_properties(file_path):
    if not os.path.exists(file_path):
        # 如果文件不存在，创建默认配置
        config = configparser.ConfigParser()
        config['DEFAULT'] = {
            'logger.debug': 'True'
        }
        with open(file_path, 'w', encoding='utf-8') as f:
            config.write(f)
    else:
        config = configparser.ConfigParser()
        config.read(file_path, encoding='utf-8')
    return config


class Config:
    def __init__(self):
        config_path = "./config.properties"
        self.config = load_properties(config_path)
        self.config_rew = load_properties(config_rew_path)
        
        logger_debug = self.config_rew.defaults().get('logger.debug', 
                                                    self.config.defaults().get('logger.debug', 'True'))
        if logger_debug.lower() == 'true':
            logger.setLevel(level=logging.DEBUG)
        
        logger.info(f"配置加载完成")

    def get_config(self, key: str, default=None):
        return self.config_rew.defaults().get(key, self.config.defaults().get(key, default))

    def write_config(self, key: str, value: str):
        # 更新内存配置
        self.config_rew.defaults()[key] = value

        # 写入文件
        with open(config_rew_path, 'w', encoding='utf-8') as config_file:
            self.config_rew.write(config_file)
        
        logger.info(f"更新配置文件: {key} = {value}")

    def get_logger_debug(self) -> bool:
        return self.get_config('logger.debug', 'True').lower() == 'true'


config_instance = Config()